<template>
  <view class="list-page">
    <view class="card-list">
      <view class="card" v-for="(item, index) in recordList" :key="index">
        <view class="card-header">
          <text class="type-tag">{{ item.serviceType }}</text>
          <text class="status-tag" :class="item.status">{{
            item.statusText
          }}</text>
        </view>
        <view class="card-content">
          <view class="info-item">
            <text class="label">申请时间：</text>
            <text class="value">{{ item.applyTime }}</text>
          </view>
          <view class="info-item">
            <text class="label">申请人：</text>
            <text class="value">{{ item.applicantName }}</text>
          </view>
        </view>
        <view class="card-footer" :class="item.status">
          <text class="download-btn" @click="downloadAllFiles(item.fileUrl)">
            下载附件
            <text class="iconfont">📎</text>
          </text>
        </view>
      </view>
    </view>

    <!-- 申请按钮 -->
    <view class="apply-btn" @click="goToApply">
      <text class="btn-text">申请证件</text>
      <text class="iconfont">+</text>
    </view>
  </view>
</template>

<script>
import { tbDocumentApplicationsList, getDict } from '@/api/dict'
import { uploadBase64 } from '@/api/upload'
import { mapGetters } from 'vuex'
import moment from 'moment'

export default {
  data() {
    return {
      recordList: [],
      serviceTypes: [],
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  watch: {
    userInfo: {
      handler(userInfo) {
        if (userInfo.userId) {
          this.getDict()
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    getDict() {
      getDict().then(({ data }) => {
        this.serviceTypes = data.map((item) => ({
          name: item.dictValue,
          value: item.dictKey,
        }))
        if (this.userInfo.userId) {
          this.getList()
        }
      })
    },
    getList() {
      tbDocumentApplicationsList({
        userId: this.userInfo.userId,
      }).then((res) => {
        this.recordList = res.data.map((item) => {
          // 根据 serviceType 值找到对应的名称
          const serviceTypeObj = this.serviceTypes.find(
            (type) => type.value === item.serviceType
          )
          console.log(serviceTypeObj)
          return {
            applicantName: item.applicantName,
            applyTime: moment(item.createTime).format('YYYY-MM-DD HH:mm:ss'),
            statusText: !!item.resultFile ? '已完成' : '处理中',
            status: !!item.resultFile ? 'success' : 'pending',
            serviceType: serviceTypeObj ? serviceTypeObj.name : '未知类型',
            fileUrl: item.resultFile,
          }
        })
        console.log(this.recordList)
      })
    },
    handleDownload(url) {
      // 处理文件下载
      uni.downloadFile({
        url: url,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.saveFile({
              tempFilePath: res.tempFilePath,
              success: (res) => {
                uni.showToast({
                  title: '下载成功',
                  icon: 'success',
                })
              },
            })
          }
        },
        fail: () => {
          uni.showToast({
            title: '下载失败',
            icon: 'none',
          })
        },
      })
    },
    goToApply() {
      uni.navigateTo({
        url: '/pages/zjhq/index',
      })
    },
    async downloadAllFiles(filesStr) {
      if (!filesStr) return
      const JSZip = (await import('jszip')).default
      const zip = new JSZip()
      const files = filesStr.split(',').filter((item) => !!item)

      try {
        // 获取所有文件
        const fetchPromises = files.map(async (fileUrl) => {
          const response = await fetch(fileUrl)
          const blob = await response.blob()
          const fileName = fileUrl.split('/').pop()
          zip.file(fileName, blob)
        })

        await Promise.all(fetchPromises)

        // 生成zip的blob
        const content = await zip.generateAsync({ type: 'blob' })

        // 将blob转换为base64
        const reader = new FileReader()
        reader.readAsDataURL(content)
        reader.onload = () => {
          const base64Data = reader.result.split(',')[1] // 移除base64头部信息
          console.log('zip base64:', base64Data)
          uploadBase64(base64Data, 'zip').then(({ data }) => {
            const fileUrl = data.url

            // 复制下载链接到剪贴板
            uni.setClipboardData({
              data: 'https://www.zhihuilantian.com' + fileUrl,
              success: () => {
                uni.showModal({
                  title: '下载提示',
                  content: '下载链接已复制到剪贴板，请在浏览器中打开下载',
                  showCancel: false,
                  confirmText: '我知道了',
                })
              },
              fail: () => {
                uni.showToast({
                  title: '复制链接失败',
                  icon: 'none',
                })
              },
            })
          })
        }
      } catch (error) {
        console.error('下载文件失败:', error)
        uni.showToast({
          title: '下载文件失败',
          icon: 'none',
        })
      }
    },
  },
  onShow() {
    this.getDict()
  },
}
</script>

<style lang="scss" scoped>
.list-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 16px;
  position: relative; // 为固定定位的按钮提供参考
  padding-bottom: 80px; // 为底部按钮留出空间
}

.card-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.card {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;

    .type-tag {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }

    .status-tag {
      font-size: 12px;
      padding: 2px 8px;
      border-radius: 10px;

      &.success {
        color: #52c41a;
        background-color: rgba(82, 196, 26, 0.1);
      }

      &.pending {
        color: #faad14;
        background-color: rgba(250, 173, 20, 0.1);
      }

      &.failed {
        color: #ff4d4f;
        background-color: rgba(255, 77, 79, 0.1);
      }
    }
  }

  .card-content {
    padding: 8px 0;
    border-bottom: 1px solid #f0f0f0;

    .info-item {
      display: flex;
      margin-bottom: 8px;
      font-size: 14px;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        color: #666;
        width: 80px;
      }

      .value {
        color: #333;
        flex: 1;
      }
    }
  }

  .card-footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 12px;
    &.pending {
      opacity: 0.8;
      .download-btn {
        color: #c6dcf3;
      }
    }
    .download-btn {
      display: flex;
      align-items: center;
      gap: 4px;
      color: #66c2ff;
      font-size: 14px;
      cursor: pointer;

      .iconfont {
        font-size: 16px;
      }
    }
  }
}

.apply-btn {
  position: fixed;
  right: 20px;
  bottom: 20px;
  width: 120px;
  height: 44px;
  background-color: #66c2ff;
  border-radius: 22px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  box-shadow: 0 2px 8px rgba(0, 122, 255, 0.3);
  z-index: 100;

  .btn-text {
    color: #fff;
    font-size: 16px;
  }

  .iconfont {
    color: #fff;
    font-size: 20px;
  }
}
</style>
